//
//  ClubPushStrategyViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/19.
//

import UIKit
import ZLPhotoBrowser
import Photos

class ClubPushStrategyViewController: ClubBaseViewController {

    private let scrollView = UIScrollView()
    private let containerView = UIView()
    private let closeButton = c_make_ex(UIButton.self)
        .image("Common_close").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .font(16.font_semiBold).color(.black).end()
    private let sendButton = c_make_ex(UIButton.self)
        .image("Square_pushEnable").image("Square_pushDisable", state: .disabled).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(18.0.Scale).border(.black.alpha(0.1), width: 1.5).end()
    private let titleTextField = c_make_ex(UITextField.self)
        .bgColor(.clear).color("#47494D").font(16.font_semiBold)
        .placeholder("在此处输入标题").end()
    private let placeholderLabel = c_make_ex(UILabel.self)
        .text("在此处输入内容...").font(15.font_medium).color("#AEB0B3").end()
    // 创建UITextView
    private let textView: UITextView = {
        let tv = UITextView()
        tv.font = 15.font_medium
        tv.textColor = "#47494D".toColor
        tv.tintColor = "#47494D".toColor
        tv.isScrollEnabled = false  // 禁止滚动
        tv.backgroundColor = .clear
        tv.translatesAutoresizingMaskIntoConstraints = false
        return tv
    }()
    private let functionView = ClubDynamicFunctionView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var gameModels: [ClubDynamicGameModel]?
    var topicModels: [ClubDynamicGameModel]?
    
    private var hasVideo = false
    private var images: [UIImage] = []
    private var assets: [PHAsset] = []
    private var imageUrlArr = [String]()
    private var classID: String = "2" //2攻略  4问题
    var communityId: String = ""
    
    var updateDataBlock: (() -> Void)?
    
    var type: String = "" {
        didSet{
            if type == "3"{
                classID = "2"
                titleLabel.text = "发布到攻略"
            }else{
                classID = "4"
                titleLabel.text = "发布到帖子"
            }
        }
    }
    
    init() {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            scrollView.subviews{
                containerView.subviews{
                    closeButton
                    titleLabel
                    sendButton
                    iconImageView
                    titleTextField
                    textView.subviews{
                        placeholderLabel
                    }
                    functionView
                    collectionView
                }
            }
        }
        
        scrollView.backgroundColor = .clear
        containerView.backgroundColor = .clear
        scrollView.top(0).leading(0).width(.screenWidth).bottom(0)
        containerView.fillContainer().width(.screenWidth)
        closeButton.top(.statusHeight).leading(0).width(56.0.Scale).height(44.0.Scale)
        titleLabel.Leading == closeButton.Trailing
        titleLabel.CenterY == closeButton.CenterY
        sendButton.trailing(0).top(.statusHeight).height(44.0.Scale).width(88.0.Scale)
        iconImageView.leading(10).top(.navi_height+4.0).size(36.0.Scale)
        titleTextField.leading(56.0.Scale).trailing(12.0.Scale).height(24.0.Scale).top(.navi_height+8.0.Scale)
        textView.leading(56.0.Scale).trailing(12.0.Scale).top(.navi_height+36.0.Scale).height(37.0.Scale)
        placeholderLabel.leading(2).top(2)
        functionView.leading(56.0.Scale).trailing(0).height(33.0.Scale)
        functionView.Top == textView.Bottom + 3.0.Scale
        collectionView.leading(0).trailing(0).height(0).bottom(.tabBar_height)
        collectionView.Top == functionView.Bottom + 8.0.Scale
        
        sendButton.isEnabled = false
        textView.delegate = self
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        titleTextField.placehold("#AEB0B3".toColor, font: 16.font_semiBold)
        titleTextField.delegate = self
        closeButton.addTarget(self, action: #selector(clickCloseButton), for: .touchUpInside)
        functionView.imgStr = ["Square_pushPic"]
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 2.0.Scale
        layout.minimumInteritemSpacing = 2.0.Scale
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 0, left: 56.0.Scale, bottom: 0, right: 16.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubGameCircleCell.self, forCellWithReuseIdentifier: ClubGameCircleCell.description())
        collectionView.showsVerticalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        functionView.functionButtonBlock = { funcID in
            self.checkPhotoLibraryPermission()
            self.textView.resignFirstResponder()
        }
        
        
        iconImageView.loadImage(url: ClubUser.face)
        sendButton.addTarget(self, action: #selector(clickSendButton), for: .touchUpInside)
    }
    
    @objc private func clickCloseButton(){
        self.dismiss(animated: true)
    }
    
}

//MARK: Action
extension ClubPushStrategyViewController {
    
   private func checkPhotoLibraryPermission() {
        let status = PHPhotoLibrary.authorizationStatus()
            
        switch status {
            case .authorized:
                // 已经授权，继续访问相册
            DispatchQueue.main.async {
                self.showPhotoLibrary()
            }
                
            case .denied, .restricted:
                // 用户拒绝或受限，无法访问相册
                print("用户拒绝访问相册")
            case .notDetermined:
                // 用户还没有决定是否允许访问，进行请求
                PHPhotoLibrary.requestAuthorization { newStatus in
                    if newStatus == .authorized {
                        // 用户授权，继续访问相册
                        DispatchQueue.main.async {
                            self.showPhotoLibrary()
                        }
                    } else {
                        print("用户拒绝访问相册")
                    }
                }
        @unknown default:
                print("未知的权限状态")
        }
    }
    
    private func showPhotoLibrary() {
        if hasVideo {
            "请删除视频后重选".toast_error
            return
        }
        let config = ZLPhotoConfiguration.default()
        
        config.languageType = .chineseSimplified
        config.maxSelectCount = 9
        config.allowSelectGif = false
        config.allowMixSelect = false
        config.allowSelectVideo = false
        config.allowTakePhotoInLibrary = true
        config.allowEditVideo = true
        config.maxEditVideoTime = 30
        config.maxRecordDuration = 30
        config.editAfterSelectThumbnailImage = true
        config.allowSelectOriginal = false
        config.animateSelectBtnWhenSelect = false
        config.cropVideoAfterSelectThumbnail = true
        let ac = ZLPhotoPreviewSheet(selectedAssets:assets)
        
        ac.selectImageBlock = { [weak self] (images, assets, isOriginal) in
            self?.hasVideo = assets.first?.mediaType == .video
            self?.images = images
            self?.assets = assets
            self?.loadImageData()
        }
        ac.showPhotoLibrary(sender: self)
    }
    
    @objc private func clickSendButton(){

        let titleText = titleTextField.text ?? ""
        let contentText = textView.text ?? ""
        
        if titleText.count <= 0 {
            "请输入发布标题".toast_error
            return
        }
        if contentText.count <= 0 {
            "请输入发布内容".toast_error
            return
        }
        ToastUtil.show()
        if hasVideo {
            ZLPhotoManager.fetchAssetFilePath(asset: self.assets.first!) { path in
                let videoData =  try? Data(contentsOf: URL(string: path ?? "")!)
                let suffix = URL(string: path ?? "")!.pathExtension
                RaeRequestParameterConfig.shared.uploadImage(uploadImage: self.images.first!) { urlString in
                    RaeRequestParameterConfig.shared.uploadVideo(record: videoData!, suffix: suffix) { videoUrl in
                        self.addDynamic(title: titleText, content: contentText, imgs: urlString, video: videoUrl)
                    } failure: { errorMessage in
                        
                    } progress: { pro in
                        
                    }

                } failure: { errorMessage in
                    
                }

            }
        }
        if self.images.count > 0 {
            updateImage(title: titleText, content: contentText)
        }else{
            addDynamic(title: titleText, content: contentText, imgs: "", video: "")
        }

    }
    
    private func addDynamic(title: String, content: String, imgs: String, video: String){
        
        Task{

            let dict: [String: Any] = ["content": content, "image": imgs, "video": video, "class_id": self.classID, "title": title, "pid" : self.communityId]
            let res = await self.network.requestSpecial(.pushCommunityPost(json: dict))
            ToastUtil.dismiss()
            if res.isSuccess {
                self.updateDataBlock?()
                self.dismiss(animated: true)
            }else{
                res.errorMessage?.toast_error
            }
        }
    }
    
    private func updateImage(title: String, content: String){
        self.imageUrlArr.removeAll()
        let upLoadImageGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "GameDetailupLoadForumImage")
        for i in 0..<images.count {
            upLoadImageGroup.enter()
            
            workingQueue.async {

                RaeRequestParameterConfig.shared.uploadImage(uploadImage: self.images[i]) { urlString in
                    self.imageUrlArr.append(urlString)
                    upLoadImageGroup.leave()
                } failure: { errorMessage in
                    upLoadImageGroup.leave()
                }
            }
        }
        upLoadImageGroup.notify(queue: workingQueue) {
            self.addDynamic(title: title, content: content, imgs: self.imageUrlArr.joined(separator: ","), video: "")
        }
    }
}

//MARK: TextView
extension ClubPushStrategyViewController: UITextViewDelegate, UITextFieldDelegate {
    
    // UITextViewDelegate 方法
    func textViewDidChange(_ textView: UITextView) {
        // 计算文本内容的高度
        let size = CGSize(width: textView.frame.width, height: .infinity)
        let estimatedSize = textView.sizeThatFits(size)
        // 更新高度约束
        textView.heightConstraint?.constant = estimatedSize.height
        
        // 根据内容决定是否隐藏占位符
        placeholderLabel.isHidden = !textView.text.isEmpty
        self.updateSendButtonState()
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        // 开始编辑时隐藏占位符
        placeholderLabel.isHidden = true
    }
        
    func textViewDidEndEditing(_ textView: UITextView) {
        // 结束编辑时，如果内容为空，显示占位符
        if textView.text.isEmpty {
            placeholderLabel.isHidden = false
        }
    }
    
    
    // 监听输入变化
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        self.updateSendButtonState()
        return true // 返回 true 允许输入
    }

    private func updateSendButtonState(){
        
        if (titleTextField.text?.count ?? 0) > 0 && self.textView.text.count > 0 {
            sendButton.isEnabled = true
        }else{
            sendButton.isEnabled = false
        }
    }
}

//MARK: UICollectionViewDelegate, UICollectionViewDataSource
extension ClubPushStrategyViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if hasVideo {
            return 1
        }else{
            return images.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let pageCell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubGameCircleCell.description(), for: indexPath) as? ClubGameCircleCell else { return UICollectionViewCell() }
        pageCell.imageView.image = images[indexPath.row]
        pageCell.playImage.isHidden = !hasVideo
        pageCell.index = indexPath.row
        pageCell.delButton.isHidden = false
        pageCell.delBlock = { delIndex in
            self.images.remove(at: delIndex)
            self.assets.remove(at: delIndex)
            self.hasVideo = false
            self.collectionView.reloadData()
        }
        pageCell.layoutIfNeeded()
        if images.count == 1 {
            pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 8.0.Scale)
        }else if images.count == 2 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
            }else {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 3 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight,.bottomRight], radius: 8.0.Scale)
            }else {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 4 || images.count == 5{
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 3 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
            
        }else if images.count == 6 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 3 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 5 {
                pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 7 || images.count == 8{
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 6 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 6 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 8 {
                pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }
        
        return pageCell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if hasVideo {
            return CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
        }else if images.count == 1 {
            return CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
        }else if images.count == 2{
            
            return CGSize (width: (CGFloat.screenWidth - 74.0.Scale)/2.0, height: 90.0.Scale)
        }else{
            
            return CGSize (width: (CGFloat.screenWidth - 76.0.Scale)/3, height: (CGFloat.screenWidth - 76.0.Scale)/3)
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let vc = ZLImagePreviewController(datas: self.assets, index: indexPath.row, showSelectBtn: false) { (url) -> ZLURLType in
            if self.hasVideo {
                return .video
            }else {
                return .image
            }
            
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
}


//MARK: data
extension ClubPushStrategyViewController {
    
    private func loadData(){
        
//        Task {
//            let models = await network.request(.dynamicTopic,type: ClubDynamicGameModel.self)
//            if models.isSuccess, let models = models.models {
//                var tempModels = [ClubDynamicGameModel]()
//                for var md in models {
//                    md.type = "1"
//                    tempModels.append(md)
//                }
//                self.topicModels = tempModels
//            }
//        }
        
//        Task {
//            let models = await network.request(.dynamicGame,type: ClubDynamicGameModel.self)
//            if models.isSuccess, let models = models.models {
//                var tempModels = [ClubDynamicGameModel]()
//                for var md in models {
//                    md.type = "2"
//                    tempModels.append(md)
//                }
//                self.gameModels = tempModels
//            }
//        }
    }
    
    private func loadImageData(){
        
        if hasVideo {
            
            collectionView.heightConstraint?.constant = 152.0.Scale
        }else {
            
            if images.count == 1 {
                collectionView.heightConstraint?.constant = 152.0.Scale
            }else if images.count == 2 {
                collectionView.heightConstraint?.constant = 90.0.Scale
            }else if images.count > 2 {
                let index = (images.count + 2) / 3
                collectionView.heightConstraint?.constant = (CGFloat.screenWidth - 76.0.Scale)/3 * CGFloat(index)
            }else{
                collectionView.heightConstraint?.constant = 0
            }
        }
        collectionView.reloadData()
    }
}
